#include <QtGui>

#include "gudaywellwidget.h"
#include "generateid.h"

GudaywellWidget::GudaywellWidget(QString table,QWidget *parent)
	:QTableView(parent)
{
	this->table = table;
	initializeModel();
	this->setItemDelegate(new QSqlRelationalDelegate(this));
	
	this->verticalHeader()->hide();
	this->setEditTriggers(QAbstractItemView::AllEditTriggers);
	this->setAlternatingRowColors(true);
    this->resizeRowsToContents();
    
    this->setColumnWidth( 0, 120 );
    this->setColumnWidth( 1, 70 );
    this->setColumnWidth( 2, 70 );
    this->setColumnWidth( 3, 70 );
    this->setColumnWidth( 4, 120 );
    
    connect(model, SIGNAL(beforeInsert(QSqlRecord &)),
            this, SLOT(beforeInsert(QSqlRecord &)));
	connect(model,SIGNAL(beforeDelete(int)),this,SLOT(beforeDelete()));
}

void GudaywellWidget::initializeModel()
{
	 model = new QSqlRelationalTableModel(this);
	 model->setTable(table);
	 model->select();
     model->setEditStrategy(QSqlTableModel::OnFieldChange);
     
     model->setRelation(1, QSqlRelation("subjects", "id", "name"));
     model->setRelation(2, QSqlRelation("times", "id", "name"));
     model->setRelation(3, QSqlRelation("times", "id", "name"));
     model->setRelation(4, QSqlRelation("places", "id", "name"));
     model->setRelation(5, QSqlRelation("teachers", "id", "name"));

     model->setHeaderData(1, Qt::Horizontal, QObject::tr("Subject"));
     model->setHeaderData(2, Qt::Horizontal, QObject::tr("From"));
     model->setHeaderData(3, Qt::Horizontal, QObject::tr("To"));
     model->setHeaderData(4, Qt::Horizontal, QObject::tr("Place"));
     model->setHeaderData(5, Qt::Horizontal, QObject::tr("Teacher"));
     
     this->setModel(model);
}

void GudaywellWidget::addRow()
{   
    int row = model->rowCount();
    //model->insertRow(row);
    QSqlQuery q;
    q.exec( QString("insert into %1 values( %2,0,0,0,0,0)").arg(table).arg(generateId(table)) );
    model->select();
    QModelIndex index = model->index(row, 0);
    this->setCurrentIndex(index);
    this->edit(index);
}

void GudaywellWidget::delRow()
{
	QModelIndex index = this->currentIndex();
    if (!index.isValid())
        return;
    model->removeRow(this->currentIndex().row());
}

void GudaywellWidget::refresh()
{
	model->select();
	this->resizeRowsToContents();
}

void GudaywellWidget::beforeInsert(QSqlRecord &record)
{
	record.setValue("id", generateId(table));
    emit modified();
}

void GudaywellWidget::beforeDelete()
{
	emit modified();
}
